package com.mall.common;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mall.exception.MallExceptionEnum;

/**
 * 统一响应结果封装
 * @param <T>
 */
public class Result<T> {
    //统一响应码
    private Integer status;
    //统一响应信息
    private String msg;
    //统一响应数据
    private T data;
    //响应正常状态码
    private static final Integer OK_CODE = 10000;
    //响应正常信息
    private static final String OK_MSG = "SUCCESS";

    //构造方法
    public Result(Integer status, String msg, T data) {
        this.status = status;
        this.msg = msg;
        this.data = data;
    }
    public Result(Integer status, String msg) {
        this.status = status;
        this.msg = msg;
    }
    public Result() {
        this(OK_CODE,OK_MSG);
    }

    //封装响应成功的结果
//    封装有状态码和状态信息和获取的数据的、
    public static <T> Result<T> success(T data){
        Result<T> result = new Result();
        result.setData(data);
        return  result;
    }
//    封装只有状态码和状态信息的
    public static Result success(){
//        只要是newResult（），即默认返回的是无数据的的成功信息
        return new Result();
    }
    //封装响应失败的结果
    public static Result error(Integer status,String msg){
        return new Result(status,msg);
    }
    //封装响应失败的结果
    public static  Result error(MallExceptionEnum exception){
        return error(exception.getStatus(),exception.getMsg());
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "Result{" +
                "status=" + status +
                ", msg='" + msg + '\'' +
                ", data=" + data +
                '}';
    }

    public static void main(String[] args)throws Exception  {
        ObjectMapper objectMapper = new ObjectMapper();
        System.out.println(objectMapper.writeValueAsString(Result.success("hh")));
        System.out.println(objectMapper.writeValueAsString(Result.error(MallExceptionEnum.NEED_USERNAME)));
        System.out.println(Result.success());
        System.out.println(Result.error(MallExceptionEnum.SYSTEM_ERROR));
    }
}